import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter_business_1803a/bean/cartInfo_result.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CartProvide with ChangeNotifier {
  String cartString = "[]"; //存到sp中的String
  List<CartInfoResult> cartList = []; //从sp中读取到的list

  //存到sp中
  save(goodsId, goodsName, count, price, images) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    cartString = sharedPreferences.getString('cartInfo'); //获取持久化存储的值
    print('cartString:$cartString');
    //判断cartString是否为空,为空就说明是第一次添加,或者key被清除掉了
    //如果有值记性decode操作
    var temp = cartString == null ? [] : json.decode(cartString.toString());
    //把获取到的值转换成list
    List<Map> tempList = (temp as List).cast();
    //声明变量,用于判断购物车中是否已经存在此商品,通过ID来进行判断
    var isHave = false;
    int ival = 0; //用于循环

    tempList.forEach((item) {
      //进行循环,找出是否已经存在该商品
      //如果存在,数量进行+1操作
      if (item['goodsId'] == goodsId) {
        tempList[ival]['count'] = item['count'] + 1;
        cartList[ival].count++;
        isHave = true;
      }
      ival++;
    });

    if (!isHave) {
      Map<String, dynamic> newGood = {
        'goodsId': goodsId,
        'goodsName': goodsName,
        'count': count,
        'price': price,
        'images': images
      };
      tempList.add(newGood);
      cartList.add(new CartInfoResult.fromJson(newGood));
    }
    //把字符进行encode操作
    cartString = json.encode(tempList).toString();
    print(cartString);
    print(cartList.toString());
    sharedPreferences.setString('cartInfo', cartString);
  }

  remove() async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    sharedPreferences.remove('cartInfo');
    print('清空完成');
    notifyListeners();
  }
}
